package com.project.RocketRoute.executor;

import com.alibaba.fastjson.JSONObject;
import com.project.annotation.rocket.SendMethod;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Aspect
@Component
public class RocketSendAop {

    @Autowired
    RocketMqProductExecutor rocketMqProductExecutor;

    @Pointcut("@annotation(com.project.annotation.rocket.SendMethod)")
    public void rocketSend() {
    }

    @Around("rocketSend() && @annotation(sendMethod)")
    public Object Interceptor(ProceedingJoinPoint pjp, SendMethod sendMethod) throws Throwable {
        try
        {
            Object rtn = pjp.proceed();

            if (null != rtn) {
                List<String> jsons = new ArrayList<>();
                for (Object ob : pjp.getArgs()) {
                    jsons.add(JSONObject.toJSONString(ob));
                }

                rocketMqProductExecutor.sendGroup(sendMethod.groupId(), sendMethod.topic(), sendMethod.tags(), jsons.toArray(new String[] {}));
                return rtn;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
